package com.happyscan138.makefun;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.happyscan138.makefun.base.VideoPlayView;
import com.happyscan138.makefun.base.share;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.Urls.Urls.creat;
import static com.happyscan138.makefun.base.Uri.getPhotoPathFromContentUri;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.happyscan138.makefun.base.share.access_key;
import static com.happyscan138.makefun.base.share.preferences;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/19.
 */

public class creatBattle extends AppCompatActivity implements View.OnClickListener, VideoPlayView.MediaPlayerImpl {
    private ImageButton buttonBack,buttonInputVideo,buttonInputSaoku;
    private Button buttonRelease;
    private EditText editTextSubject;
    private VideoView videoView;
    private ImageView videoImage;
    private String textAnswer;
    private ImageButton videoPlayBtn;
    private String path;
    private  File file;
    private MediaController mMediaCtrl;
    private static final long MAX_POST_SIZE = 4 * 1024 * 1024;
    private PopupWindow pop;
    private ImageButton Saoku;
    private Intent intent;
    private LayoutInflater inflater;
    private boolean isPlaying;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.creat_new_battle);
        initView();
        share.preferences= getSharedPreferences("UserInfo", MODE_PRIVATE);
        access_key=preferences.getString("UserId","");
    }

    public void initView() {
        inflater = LayoutInflater.from(this);
        TextChange textChange = new TextChange();
        buttonBack = (ImageButton) findViewById(R.id.creatBattle_back);
        buttonBack.setOnClickListener(this);
        buttonRelease = (Button) findViewById(R.id.creatBattle_Release);
        buttonRelease.setOnClickListener(this);
        editTextSubject = (EditText) findViewById(R.id.creatBattle_text);
        editTextSubject.addTextChangedListener(textChange);
        videoView = (VideoView) findViewById(R.id.battle_new_videoview);
  //      imageViewBackgroud = (ImageView) findViewById(R.id.battle_new_video_image);
        buttonInputVideo = (ImageButton) findViewById(R.id.creatBattle_video);
        buttonInputVideo.setOnClickListener(this);
        buttonInputSaoku = (ImageButton) findViewById(R.id.creatBattle_Saoku);
        buttonInputSaoku.setOnClickListener(this);
        videoPlayBtn = (ImageButton) findViewById(R.id.creatbattle_new_video_play_btn);
        videoPlayBtn.setOnClickListener(this);
        videoImage = (ImageView) findViewById(R.id.creatbattle_new_video_image);
        mMediaCtrl = new MediaController(this, false);
        Saoku=(ImageButton)findViewById(R.id.creatBattle_Saoku);
        Saoku.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.creatBattle_Saoku:
                log.e("onclick","onclick");
                intent =new Intent();
                intent.setClass(creatBattle.this,Saoku.class);
                startActivityForResult(intent,001);
                break;
            case R.id.creatBattle_back:
                finish();
                break;
            case R.id.creatBattle_video:
                Intent intent=new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,000);
                break;

            case R.id.creatBattle_Release:
                if(path==null){
                    Toast.makeText(this,"请输入内容",Toast.LENGTH_LONG).show();
                }else {

                    client = new AsyncHttpClient();
                    params = new RequestParams();
                    params.put("access_key", access_key);
                    params.put("type_id", "5");
                    params.put("content", textAnswer);
                    params.put("answer_json", "0");
                    file = new File(path);
                    long length = file.length();
                    if (length > MAX_POST_SIZE) {
                        Toast.makeText(this, "上传文件视频大于4M", Toast.LENGTH_SHORT).show();
                        log.e("length",length+"");
                        break;
                    } else {
                        try {
                            params.put("file", file);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        //弹出popuwindow
                        if(pop==null) {
                            LayoutInflater inflater = LayoutInflater.from(this);
                            View view = inflater.inflate(R.layout.waiting, null);
                            pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, false);
                            pop.setOutsideTouchable(false);
                            pop.setFocusable(true);
                            setWindowBackgroundAlpha(0.5f);
                            ImageView loadingImg = (ImageView) view.findViewById(R.id.loading_imageView_info);
                            Animation anim = AnimationUtils.loadAnimation(this, R.anim.tip);
                            loadingImg.startAnimation(anim);
                            pop.showAsDropDown(view);
                        }
                        Log.e("params", params.toString());
                        RequestHandle handle = client.post(creat, params, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                super.onSuccess(statusCode, headers, response);
                                Log.e("onSuccess", response.toString());
                                String jsonStr = response.toString();
                                try {
                                    JSONObject jsonObject = new JSONObject(jsonStr);
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(creatBattle.this, msg, Toast.LENGTH_SHORT).show();
                                    // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                                    pop.dismiss();
                                    int i = jsonObject.getInt("code");
                                    if (i == 1) {
                                        startActivity(new Intent(creatBattle.this, MainActivity.class));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                super.onFailure(statusCode, headers, responseString, throwable);
                                Log.e("onFailure", responseString);
                            }
                        });
                        break;
                    }
                }
            case R.id.creatbattle_new_video_play_btn:
                    if(path==null){
                    Toast.makeText(this,"请选择视频",Toast.LENGTH_LONG).show();
                }else {
                    videoImage.setVisibility(View.INVISIBLE);
                    videoPlayBtn.setVisibility(View.INVISIBLE);
                    videoView.setVisibility(View.VISIBLE);
                    videoView.setMediaController(mMediaCtrl);
                    videoView.setVideoPath(path);
                    videoView.requestFocus();
                    videoView.start();
                    break;
                }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==000&&resultCode== Activity.RESULT_OK&&data!=null) {
            Uri uri = data.getData();
            path = getPhotoPathFromContentUri(this, uri);
        }
        if(requestCode==001&&resultCode==1&&data!=null){
            Bundle bundle = data.getExtras();
            String a=bundle.getString("SaokuText");
            String video=bundle.getString("SaokuVideo");
            log.e("video",video);
            if(a!=null) {
                editTextSubject.setText(a);
                textAnswer = a;
                log.e("Subject",textAnswer);
            }else if(video!=null){
                log.e("video",video);
                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.saoku_video_item, null);
                replaceVieo(video,layout);
                RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.Saobo_layout);
                linearLayout.removeView(findViewById(R.id.creatbattle_new_video_image));
                linearLayout.addView(layout);
                path=video.substring(28);

            }
        }

    }
    private void setWindowBackgroundAlpha(float alpha) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = alpha;
        getWindow().setAttributes(layoutParams);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onExpend() {

    }

    @Override
    public void onShrik() {

    }


    //EditText的监听器
    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            textAnswer =editTextSubject.getText().toString();

        }
    }
    private void replaceVieo(final String path,LinearLayout layout){
        ImageView play=(ImageView)layout.findViewById(R.id.saoku_play_btn);
        final VideoPlayView playView=(VideoPlayView)layout.findViewById(R.id.saoku_video_play_view);
        final FrameLayout showLayout=(FrameLayout)layout.findViewById(R.id.saoku_show_layout);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPlaying = true;
                showLayout.setVisibility(View.GONE);
                playView.setUrl(path);
                setPlayView(playView);
                playView.openVideo();
                playView.setVisibility(View.VISIBLE);
            }
        });
    }
    public void setPlayView(VideoPlayView playView) {
        playView.setMediaPlayerListenr(this);
    }
}
